package com.ms.qw.jsf.datamodel;

import com.ms.qw.application.mappers.ColegioMapper;
import com.ms.qw.application.mappers.RecetaMapper;
import com.ms.qw.client.dto.*;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SelectableDataModel;
import org.primefaces.model.SortOrder;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class LazyColegioModel extends LazyDataModel<ColegioDTO>
        implements SelectableDataModel<ColegioDTO> {

    ColegioMapper colegioMapper;
    private ColegioFlt colegioFlt;
    private List<ColegioDTO> colegioList= new ArrayList<ColegioDTO>();



    public LazyColegioModel(ColegioMapper mapper, ColegioFlt colegioFlt) {
        this.colegioMapper = mapper;
        this.colegioFlt=colegioFlt;
    }

    private Integer calcularTamanioTotal() {
        Integer numeroNotificaciones = colegioMapper.total(colegioFlt);
        return numeroNotificaciones < 500 ? numeroNotificaciones:500;
    }

    @Override
    public List<ColegioDTO> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {

        Integer totalSize= calcularTamanioTotal();
        int start = first;
        int end = first + pageSize;

        if(end> totalSize){
            end=totalSize;
        }
        colegioFlt.setStart(start);
        colegioFlt.setEnd(end);
        colegioList = colegioMapper.find(colegioFlt);
        setRowCount(totalSize);
        System.out.println(colegioFlt.getDistrito().getCodigo()+" "+colegioList.size());
        return colegioList;
    }


    @Override
    public ColegioDTO getRowData(String rowKey) {
        for(ColegioDTO n : colegioList) {
            if(n.getCodigo().equals(Integer.valueOf(rowKey)))
                return n;
        }

        return null;
    }

    @Override
    public Object getRowKey(ColegioDTO n) {
        return n.getCodigo();
    }

    @Override
    public void setRowIndex(int rowIndex) {
        if (rowIndex == -1 || getPageSize() == 0) {
            super.setRowIndex(-1);
        } else{

            super.setRowIndex(rowIndex % getPageSize());
        }

    }

}
